import React, {useMemo, useRef} from 'react';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';

const AreaChartsBookStat = ({
                                buy_data = [],
                                sell_data = [],
                                exchange = '',
                                selectedData,
                                stats_batch = []
                            }) => {
    const chartContainerRef = useRef(null); //
    // 假设 stats_map 数据已经从后端传递过来

    // 提取价格和买卖量数据

    const currentPrice = stats_batch
        .filter(item => item.exchange === exchange)  // 过滤出 exchange 为 "binance" 的项
        .map(item => item.current_price);
    const buyPrices = buy_data.map(item => item.price);
    const buyVolumes = buy_data.map(item => parseFloat(item.total_volume));
    const buyCumulativeVolumes = buy_data.map(item => parseFloat(item.cumulative_volume));

    const sellPrices = sell_data.map(item => item.price);
    const sellVolumes = sell_data.map(item => parseFloat(item.total_volume));
    const sellCumulativeVolumes = sell_data.map(item => parseFloat(item.cumulative_volume));

    // 合并买卖价格和对应的数量
    const prices = [...buyPrices, ...sellPrices]; // 合并买入和卖出价格

    const volumes = [...buyVolumes, ...sellVolumes]; // 合并买入和卖出数量

    const getPlotLineValue = (currentPrice, prices) => {
        // 查找 currentPrice 所在的区间
        for (let i = 0; i < prices.length - 1; i++) {
            if (currentPrice >= prices[i] && currentPrice <= prices[i + 1]) {
                // 计算 currentPrice 在两个价格之间的插值位置
                const lowerPrice = prices[i];
                const upperPrice = prices[i + 1];
                const interpolatedValue = (currentPrice - lowerPrice) / (upperPrice - lowerPrice);
                // 返回插值的位置
                return i + interpolatedValue; // 返回插值后的位置
            }
        }
        return null; // 如果没有找到对应的区间，返回 null
    };

    const plotLineValue = getPlotLineValue(currentPrice[0], prices); // 获取插值后的虚拟位置

    const series = [
        selectedData.includes('buyVolumes') && {
            name: '单点买卖单',
            data: volumes
        },
        selectedData.includes('buyCumulativeVolumes') && {
            name: '买单累计',
            data: buyCumulativeVolumes
        },
        selectedData.includes('sellCumulativeVolumes') && {
            name: '卖点累计',
            data: sellCumulativeVolumes
        },
    ].filter(Boolean); // 去除空值

    // 图表配置
    const options = {
        chart: {
            type: 'area',
            style: {
                fontSize: '1em'
            },
        },
        title: {
            text: exchange +"      "+currentPrice,
            align: 'left'
        },
        yAxis: {
            title: {
                text: 'Volume'
            },
            min: 0, // 设置Y轴最小值为0
            max: Math.max(...buyVolumes, ...sellVolumes) * 1.1, // 动态设置最大值为数据的最大值 + 10%
            labels: {
                formatter: function () {
                    return this.value; // 格式化标签为数字
                }
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
        },
        xAxis: {
            categories: prices, // 设置 x 轴为买卖价格
            title: {
                text: ''
            },
            plotLines: plotLineValue !== null ? [{
                value: plotLineValue, // 使用插值后的值
                color: 'red',
                width: 2,
                dashStyle: 'ShortDash',
                label: {
                    text: `Price: ${currentPrice[0]}`,
                    align: 'right',
                    style: {
                        color: 'red'
                    }
                },
                zIndex: 5
            }] : []
        },
        series: series,
        tooltip: {
            headerFormat: '<b>{point.x}</b><br>', // 显示时间（X轴）
            pointFormat: '{series.name}: {point.y}', // 显示每个数据点的值
            shared: true, // 显示多个系列的数据
            crosshairs: true, // 显示十字准线
        },
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 500
                },
                chartOptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalAlign: 'bottom'
                    }
                }
            }]
        },
        credits: {
            enabled: false
        }
    };

    // 全屏切换功能
    const toggleFullScreen = () => {
        if (!document.fullscreenElement) {
            chartContainerRef.current.requestFullscreen().catch(err => {
                console.error(`Error attempting to enable full-screen mode: ${err.message}`);
            });
        } else {
            document.exitFullscreen();
        }
    };

    return (
        <div ref={chartContainerRef} style={{ cursor: 'pointer' }}>
            <HighchartsReact
                highcharts={Highcharts}
                options={options}
            />
        </div>
    );
};

export default AreaChartsBookStat;
